package lk.icta.core.dao.impl;

import lk.icta.common.dao.impl.BaseDAO;
import lk.icta.core.dao.HolderDAO;
import lk.icta.core.entity.Holder;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.List;

/**
 * @author Duminda Dharmakeerthi
 */
public class HolderDAOImpl extends BaseDAO implements HolderDAO {
    @Transactional(propagation = Propagation.MANDATORY)
    public void addHolder(Holder holder, User user) {
        logger.debug("Adding a holder {} by {}", holder.getName(), user.getUsername());
        em.persist(holder);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public void updateHolder(Holder holder, User user) {
        logger.debug("Updating the holder {} by {}", holder.getName(), user.getUsername());
        em.merge(holder);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public Holder getHolderById(long holderId, User user) {
        logger.debug("Find holder {} by {}", holderId, user.getUsername());
        return em.find(Holder.class, holderId);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public Holder getHolderByRegistrationNumber(String registrationNo, User user) {
        logger.debug("Find holder related to registration no {} by {}", registrationNo, user.getUsername());
        Query q = em.createNamedQuery("getHolderByRegistrationNumber");
        q.setParameter("registrationNumberOrNIC", registrationNo);
        return (Holder) q.getSingleResult();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Holder> getHolderByName(String name, User user) {
        logger.debug("Find holders related to name {} by {}", name, user.getUsername());
        Query q = em.createNamedQuery("getHolderByName");
        q.setParameter("name", name);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Holder> findAllHolders() {
        logger.debug("Find all holders");
        Query q = em.createNamedQuery("findAllHolders");
        return q.getResultList();
    }
}
